//
//  CZComposeViewController.swift
//  GZWeibo666
//
//  Created by ksl on 15/12/5.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

enum CZComposeViewControllerType: Int {
    case Compose = 1
    case Repost = 2
    case Comment = 3
}

class CZComposeViewController: UIViewController {
    
    //MARK: - 属性
    ///微博模型
    var status: CZStatus?
    
    ///toolBar底部约束
    private var toolBarBottomCon: NSLayoutConstraint?
    
    ///控制器类型
    private var controllerType: CZComposeViewControllerType
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init(controllerType: CZComposeViewControllerType) {
        self.controllerType = controllerType
        super.init(nibName: nil, bundle: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //需要设置背景颜色,不设置会导致弹出动画有问题
        view.backgroundColor = UIColor.whiteColor()
        
        //把自定义键盘的控制器管理起来
        addChildViewController(emoticonVC)
        
        //准备 UI
        prepareUI()
        
        //监听键盘的弹出和关闭
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        }
    
    /*
    willChangeFrame: NSConcreteNotification 0x7fa482c24790 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
    UIKeyboardAnimationCurveUserInfoKey = 7;
    UIKeyboardAnimationDurationUserInfoKey = "0.25";    // 动画时间
    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
    UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";   // 键盘最终的位置
    UIKeyboardIsLocalUserInfoKey = 1;
    }}
    */
    
    //监听键盘的 frame 将要改变
    func willChangeFrame(notification: NSNotification) {
        print("willChangeFrame: \(notification)")
        
        //动画时间
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        
        //键盘的最终位置
        let endFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue
        
        //toolBar 动画到指定的位置
        //toolBar底部约束的值 = 屏幕的高度 - 键盘 frame.origin.y
        toolBarBottomCon?.constant = -(UIScreen.height() - endFrame!.origin.y)
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }

    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //MARK: - 准备 UI
    ///准备 UI
    private func prepareUI() {
        setupNavigationBar()
        setupTextView()
        setupToolBar()
    }
    
    ///设置导航栏
    private func setupNavigationBar() {
        
        //设置按钮,左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        //设置按钮,右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        
        //设置发送按钮不可用
        navigationItem.rightBarButtonItem?.enabled = false
        
        setupTitleView()
    }
    
    ///设置导航栏标题
    private func setupTitleView() {
        
        //默认发微博
        var prefix = "发微博"
        if controllerType == CZComposeViewControllerType.Repost {
            prefix = "转发微博"
        } else if controllerType == CZComposeViewControllerType.Comment {
            prefix = "评论微博"
        }
        
        //获取用户的名称
        if let name = CZUserAccount.loadUserAccount()?.screen_name {
            
            //有用户名
            let titleName = prefix + "\n" + name
            
            //创建 label
            let label = UILabel()
            
            //设置属性文本
            label.numberOfLines = 0
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(14)
            label.textColor = UIColor.blackColor()
            
            //创建可变的属性文本
            let attrString = NSMutableAttributedString(string: titleName)
            
            //获取 range
            let nameRange = (titleName as NSString).rangeOfString(name)
            
            //设置属性文本的属性
            attrString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: nameRange)
            
            attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)
            
            //顺序不能搞错
            //设置文本属性
            label.attributedText = attrString
            //适应大小
            label.sizeToFit()
            
            navigationItem.titleView = label
        } else {
            //没有用户名
            navigationItem.title = prefix
        }
    }
    
    ///设置 toolBar
    private func setupToolBar() {
        //添加子控件
        view.addSubview(toolBar)
        
        //添加约束
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.width(), height: 44))
        
        //获取 toolBar 底部约束
        toolBarBottomCon = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        //添加按钮
        
        //每个 item 对应的图片名称
        //这个数组里面的每个元素是一个字典
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "moticon"],
            ["imageName": "compose_addbutton_background", "action": "add"]]
        
        //存放 UIBarButtonItem
        var items = [UIBarButtonItem]()
        
        //通过 for 遍历数组里面的图片名称
        for dict in itemSettings {
            
            //获取到每个字典,获取字典 key 为 imageName value 图片的名称
            let imageName = dict["imageName"]!
            let item = UIBarButtonItem(imageName: imageName)
            
            //从字典里面获取每一图片对应的方法名称
            let action = dict["action"]!
            
            //获取UIBarButtonItem的 customView(是一个按钮)
            let button = item.customView as! UIButton
            
            button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            
            // action: 如果是字符串,可以直接赋值.如果是变量或常量,需要 Selector(action)
            //            button.addTarget(self, action: "itemClick", forControlEvents: UIControlEvents.TouchUpInside)
            
            //添加到 toolBar 里面
            items.append(item)
            
            //添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        //移除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
    }
    
    //MARK: - 按钮点击事件
    //toolBar 上面的 item 被点击
    func picture() {
        print("图片")
    }
    
    func trend() {
        print("#")
    }
    
    func mention() {
        print("@")
    }
    
    ///切换表情键盘
    func moticon() {
        print("表情键盘")
        
        //先让键盘退回去
        textView.resignFirstResponder()
        //异步执行键盘切换
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            //设置表情键盘,并不会马上切换
            //如果是系统键盘,就会切换成自定义的键盘,如果是自定义的键盘,就会切换到系统键盘
            self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil
            
            //再弹出键盘
            self.textView.becomeFirstResponder()
        }
    }
    
    func add() {
        print("+")
    }
    
    
    ///设置 TextView()
    private func setupTextView() {
        
        //添加子控件
        view.addSubview(textView)
        
        //添加约束 
        textView.ff_Fill(view)
        
        // 自动适应顶部的边距
        // scrollView或子类会自动往下滚动64
        // 前提:scrollView或子类.所在的控制器,在导航控制器里面
        // scrollView或子类必须是 控制器的view 或者 是控制器view的第一个子view
        //        automaticallyAdjustsScrollViewInsets = true
        
        //设置代理,来监听 textView 文本的改变
        textView.delegate = self
                
    }
    
    //关闭控制器
    @objc private func close() {
        //关闭键盘
        textView.resignFirstResponder()
        
        //关闭 sv 显示
        SVProgressHUD.dismiss()
        
        //关闭控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    ///发微博
    @objc private func sendStatus() {
        //获取 textView 的文本内容发送给服务器
        let text = textView.text
        
        if text == nil || text == "" {
            SVProgressHUD.showErrorWithStatus("内容不能为空")
            return
        }
        
        if controllerType == CZComposeViewControllerType.Compose {
            
            //显示正在发送 
            SVProgressHUD.showInfoWithStatus("正在发布微博", maskType: SVProgressHUDMaskType.Black)
            
            //发送微博
            CZNetworkTool.sharedInstance.sendStatus(status: text, finished: { (result, error) -> () in
                if error != nil {
                    print("error:\(error)")
                    
                    SVProgressHUD.showErrorWithStatus("请检查网络", maskType: SVProgressHUDMaskType.Black)
                    
                    return
                }
                
                print("发布微博成功:\(result)")
                
                //发送成功,直接关闭界面
                self.close()
            })
        } else if controllerType == CZComposeViewControllerType.Repost {
            //显示正在转发
            SVProgressHUD.showErrorWithStatus("正在转发微博", maskType: SVProgressHUDMaskType.Black)
            
            CZNetworkTool.sharedInstance.repostStatus(statusId: status!.id, status: text, finished: { (result, error) -> () in
                //判断是否有错
                if error != nil {
                    print("error:\(error)")
                    
                    SVProgressHUD.showErrorWithStatus("请检查网络", maskType: SVProgressHUDMaskType.Black)
                    
                    return
                }
                print("转发微博成功:\(result)")
                //转发成功,直接关闭界面
                self.close()
            })
        } else if controllerType == CZComposeViewControllerType.Comment {
            
            //显示正在评论
            SVProgressHUD.showErrorWithStatus("正在评论微博", maskType: SVProgressHUDMaskType.Black)
            
            CZNetworkTool.sharedInstance.commentStatus(statusId: status!.id, comment: text, finished: { (result, error) -> () in
                //判断是否有错
                if error != nil {
                    print("error:\(error)")
                    
                    SVProgressHUD.showErrorWithStatus("请检查网络", maskType: SVProgressHUDMaskType.Black)
                    
                    return
                }
                print("评论微博成功:\(result)")
                //评论成功,直接关闭界面
                self.close()
            })
        }
    }
    
    //MARK: - 懒加载
    ///setupToolBar
    private lazy var toolBar: UIToolbar = {
        
        let bar = UIToolbar()
        
        bar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        return bar
    }()
    
    ///textView
    private lazy var textView: CZPlaceholderTextView = {
        let tv = CZPlaceholderTextView()
        
        //当TextView 被拖动的时候就会把键盘退回,TextView能拖动
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        tv.font = UIFont.systemFontOfSize(18)
        
        tv.backgroundColor = UIColor.clearColor()
        
        tv.alwaysBounceVertical = true
        
        //设置占位文本
        tv.placeholder = "分享新鲜事"
        
        //?
        tv.bounces = true
       
        return tv
    }()
    
    ///自定义表情键盘的控制器
    private lazy var emoticonVC: EmoticonViewController = EmoticonViewController()
    
    
}


//扩展 CZComposeViewController 实现 UITextViewDelegate,来监听文本的改变

extension CZComposeViewController: UITextViewDelegate {
    
    //监听文本的改变
    func textViewDidChange(textView: UITextView) {
        //设置导航栏右边按钮的状态
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
